from dash import Input, Output, State, html, callback_context, ALL, no_update
import dash_bootstrap_components as dbc
from dash import Input, Output, State
from dash.exceptions import PreventUpdate
from flask import session
from models import db, User

def render_user_table():
    users = User.query.all()
    header = html.Thead(html.Tr([
        html.Th("ID"), html.Th("用户名"), html.Th("真实姓名"), html.Th("角色"),
        html.Th("状态"), html.Th("操作")
    ]))
    rows = []
    for u in users:
        rows.append(html.Tr([
            html.Td(u.id),
            html.Td(u.username),
            html.Td(u.real_name or ""),
            html.Td(u.role),
            html.Td("启用" if u.is_active else "禁用"),
            html.Td([
                dbc.Button("重置密码", id={"type": "reset-pw-btn", "index": u.id}, color="warning", size="sm", className="me-1"),
                dbc.Button("切换状态", id={"type": "toggle-active-btn", "index": u.id}, color="secondary", size="sm"),
                dbc.Button("编辑", id={"type": "edit-user-btn", "index": u.id}, color="info", size="sm", className="ms-1")
            ])
        ]))
    return html.Table([header, html.Tbody(rows)], className="table table-bordered user-table-blue")

# 假设你的修改密码页面有如下组件ID：
# - 当前密码输入框：'old-password-input'
# - 新密码输入框：'new-password-input'
# - 确认新密码输入框：'confirm-password-input'
# - 保存按钮：'save-password-btn'
# - 提示信息：'password-message'

def register_callbacks(dash_app):
    @dash_app.callback(
        Output("user-manage-output", "children"),
        Output("edit-user-modal", "is_open"),
        Output("edit-username-input", "value"),
        Output("edit-realname-input", "value"),
        Output("edit-role-input", "value"),
        Output("edit-active-input", "value"),
        Output("user-table", "children"),
        Input("add-user-btn", "n_clicks"),
        Input("save-edit-user-btn", "n_clicks"),
        Input({"type": "reset-pw-btn", "index": ALL}, "n_clicks"),
        Input({"type": "toggle-active-btn", "index": ALL}, "n_clicks"),
        Input({"type": "edit-user-btn", "index": ALL}, "n_clicks"),
        State("new-username-input", "value"),
        State("new-password-input", "value"),
        State("new-role-input", "value"),
        State("edit-username-input", "value"),
        State("edit-realname-input", "value"),
        State("edit-role-input", "value"),
        State("edit-active-input", "value"),
        State("user-table", "children"),
        prevent_initial_call=False
    )
    def unified_callback(
        add_click, edit_save_click, reset_clicks, toggle_clicks, edit_clicks,
        new_username, new_password, new_role,
        edit_username, edit_realname, edit_role, edit_active,
        table_children
    ):
        ctx = callback_context
        # 页面首次加载
        if not ctx.triggered:
            return no_update, False, "", "", "", "", render_user_table()
        trigger = ctx.triggered[0]["prop_id"].split(".")[0]
        import json
        # 新增用户
        if trigger == "add-user-btn":
            if not new_username or not new_password or not new_role:
                return dbc.Alert("请填写所有字段", color="danger"), False, "", "", "", "", render_user_table()
            if User.query.filter_by(username=new_username).first():
                return dbc.Alert("用户名已存在", color="danger"), False, "", "", "", "", render_user_table()
            user = User(username=new_username, role=new_role, is_active=True)
            user.set_password(new_password)
            db.session.add(user)
            db.session.commit()
            return dbc.Alert("用户添加成功", color="success"), False, "", "", "", "", render_user_table()
        # 编辑用户保存
        elif trigger == "save-edit-user-btn":
            user = User.query.filter_by(username=edit_username).first()
            if not user:
                return dbc.Alert("用户不存在", color="danger"), False, "", "", "", "", render_user_table()
            user.real_name = edit_realname
            user.role = edit_role
            user.is_active = edit_active
            db.session.commit()
            return dbc.Alert("用户信息已更新", color="success"), False, "", "", "", "", render_user_table()
        # 其它按钮（重置密码、切换状态、编辑）
        else:
            try:
                triggered_id = json.loads(trigger)
            except Exception:
                return no_update, False, "", "", "", "", render_user_table()
            user_id = triggered_id.get("index")
            user = User.query.get(user_id)
            if not user:
                return dbc.Alert("用户不存在", color="danger"), False, "", "", "", "", render_user_table()
            if triggered_id["type"] == "reset-pw-btn":
                user.set_password("123456")
                db.session.commit()
                return dbc.Alert(f"用户 {user.username} 密码已重置为123456", color="success"), False, "", "", "", "", render_user_table()
            elif triggered_id["type"] == "toggle-active-btn":
                user.is_active = not user.is_active
                db.session.commit()
                return dbc.Alert(f"用户 {user.username} 状态已切换", color="success"), False, "", "", "", "", render_user_table()
            elif triggered_id["type"] == "edit-user-btn":
                # 打开编辑弹窗并填充数据
                return no_update, True, user.username, user.real_name or "", user.role, user.is_active, render_user_table()
        return no_update, False, "", "", "", "", render_user_table()


    @dash_app.callback(
        Output('change-password-message', 'children'),
        Input('save-change-password-button', 'n_clicks'),
        State('current-password-input', 'value'),
        State('new-password-input', 'value'),
        State('confirm-password-input', 'value'),
        prevent_initial_call=True
    )
    def change_password(n_clicks, old_pwd, new_pwd, confirm_pwd):
        if not n_clicks:
            raise PreventUpdate
        user_id = session.get('user_id')
        if not user_id:
            return '未登录或会话已过期，请重新登录。'
        if not old_pwd or not new_pwd or not confirm_pwd:
            return '请填写所有密码字段。'
        if new_pwd != confirm_pwd:
            return '两次输入的新密码不一致。'
        user = User.query.get(user_id)
        if not user:
            return '用户不存在。'
        if not user.check_password(old_pwd):
            return '原密码错误。'
        user.set_password(new_pwd)
        db.session.commit()
        return '密码修改成功！'